<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h1>{{ author }}</h1>
    <button @click="addEle()">新增复选元素</button>
    <ul>
      <li
        :class="{ active: item.active }"
        @mouseenter="goInto(index)"
        @mouseleave="goOut(index)"
        v-for="(item, index) in goods"
        :key="item.id"
      >
        <input :id="index" type="checkbox" v-model="item.id" />
        <label :for="index">{{ index + 1 }} - {{ item.goodsName }}</label>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      author: `chanchaw`,
      checkedId: null,
      goods: [
        { id: 1, goodsName: "珊瑚绒", active: false },
        { id: 2, goodsName: "法兰绒", active: false },
        { id: 3, goodsName: "宝宝绒", active: false },
      ],
    };
  },

  methods: {
    addEle() {
      let maxId = 0;
      this.goods.forEach((item) => {
        if (maxId < item.id) maxId = item.id;
      });

      const varIndex = maxId + 1 + "";
      const goodsName = `新增名称${varIndex}`;
      const newObj = { id: maxId + 1, goodsName: goodsName, active: false };
      this.goods.push(newObj);
    },

    goInto(index) {
      this.goods[index].active = true;
      console.log(`设置${index}为true`);
    },

    goOut(index) {
      this.goods[index].active = false;
      console.log(`设置${index}为false`);
    },

    setActive(index) {
      for (let i = 0; i < this.goods.length; i++) {
        if (index == i) {
          this.goods[i].active = true;
          console.log(`设置${i}为true`);
        } else {
          this.goods[i].active = false;
          console.log(`设置${i}为false`);
        }
      }
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}

.active {
  background-color: red;
  color: white;
}
</style>
